#include "StdAfx.h"
#include "Service.h"
#include "Server.h"
#include "Client.h"

CService*			CService::s_pService;
SOCKET				CService::s_sock;
Service_Type		CService::s_serviceType;
bool				CService::s_isDrawing = false;
bool				CService::s_cantDraw = false;
HANDLE				CService::s_hMutexOnDraw;
HANDLE				CService::s_hMutexOnRecv;

CService::CService(void)
{
}

CService::~CService(void)
{
}

void CService::createService( Service_Type p_srvType, void* p_pParam )
{
	if( !s_pService )
	{
		switch(p_srvType)
		{
		case SVT_SERVER:
			s_pService = new CServer();
			break;
		case SVT_CLIENT:
			s_pService = new CClient();
			break;
		}
	}
	s_pService->setParameter(p_pParam);
	if( !initSocket() )
	{
		MessageBox( 0, _T("CService-createService initSocket fail!"), 0, 0 );
		return;
	}
	else
	{
		s_pService->init();
		HANDLE hThread = ::CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)recvMsg, 0, 0, NULL );
		::CloseHandle(hThread);
		if( s_hMutexOnDraw = CreateMutex( NULL, TRUE, NULL ) )
		{
			if( ERROR_ALREADY_EXISTS == GetLastError() )
			{
				MessageBox( 0, _T("CreateMutex error"), 0, 0 );
				return ;
			}
		}
	}
}

DWORD CService::recvMsg( LPVOID lpParam )
{
	while( s_pService )
	{
		if( s_pService )
			s_pService->actionOnRecvMsg();
	}
	return 0;
}

bool CService::isServiceCreated()
{
	return s_pService != NULL;
}

bool CService::initSocket()
{
	WORD	wVersionRequested;
	WSADATA	wsaData;

	wVersionRequested = MAKEWORD(2,2);

	if( WSAStartup( wVersionRequested, &wsaData) != 0 )
	{
		MessageBox( 0, _T("CServer-WSAStartup fail!"), 0, 0 );
		return false;
	}

	if( LOBYTE(wsaData.wVersion) != 2 ||
		HIBYTE(wsaData.wVersion) != 2 )
	{
		WSACleanup();
		MessageBox( NULL, _T("CServer-WSAStartup version fail!"), 0, 0 );
		return false;
	}

	if( INVALID_SOCKET == ( s_sock = socket( AF_INET, SOCK_DGRAM, 0 ) ) )
	{
		MessageBox( 0, _T("CServer-socket fail!"), 0, 0 );
		return false;
	}
	return true;
}

void CService::shutDownService()
{
	s_pService->shutDown();
	::ReleaseMutex(s_hMutexOnDraw);
}

void CService::serviceOnDraw()
{
	if( s_pService )
	{
		s_pService->service();
	}
}

void CService::serviceFinishDrawing()
{
	s_isDrawing = false;
}